package com.zbkj.client.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbkj.client.dao.DialogMapper;
import com.zbkj.client.service.DialogService;
import com.zbkj.common.model.client.message.Dialog;
import com.zbkj.common.response.client.DialogListResponse;
import com.zbkj.common.vo.client.LastMessageInfoVo;
import com.zbkj.common.model.client.message.DialogMember;
import com.zbkj.common.model.client.message.Message;
import com.zbkj.client.service.DialogMemberService;
import com.zbkj.client.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Comparator;

@Service
public class DialogServiceImpl extends ServiceImpl<DialogMapper, Dialog> implements DialogService {

    @Autowired
    private DialogMemberService dialogMemberService;
    @Autowired
    private MessageService messageService;

    @Override
    public List<DialogListResponse> getDialogList(Integer userId) {
        // 第一步：查询对话列表带头像
        List<DialogListResponse> dialogList = baseMapper.selectDialogListWithHeadImg(userId);
        
        // 第二步：循环获取每个对话的最后一条消息
        if (dialogList != null && !dialogList.isEmpty()) {
            for (DialogListResponse dialog : dialogList) {
                // 查询最后一条消息
                Message lastMsg = messageService.lambdaQuery()
                        .eq(Message::getDialogId, dialog.getDialogId())
                        .eq(Message::getIsDel, 0)
                        .orderByDesc(Message::getCreateTime)
                        .last("limit 1")
                        .one();
                
                dialog.setLastMessageInfo(lastMsg);
                if (lastMsg != null) {
                    dialog.setLastMessageTime(lastMsg.getCreateTime());
                }
            }

            // 排序：先按isTop降序，再按lastMessageTime降序（空值最后）
            dialogList.sort(
                Comparator
                    .comparing(DialogListResponse::getIsTop, Comparator.nullsLast(Comparator.naturalOrder()))
                    .reversed()
                    .thenComparing(DialogListResponse::getLastMessageTime, Comparator.nullsLast(Comparator.reverseOrder()))
            );
        }
        
        return dialogList;
    }
}